package TableAdditions;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import Tables.PromotionTableInterface;
import Utility.Customer;
import Utility.Product;


public class PromotionAddition extends JFrame {
    
	public String specialprice;
	public int promotionUnit;
	public boolean customerFlag=false;
	public boolean productFlag=false;
	public Customer[] customers;
	public Product[] products;
	public static int selectedProductIndex;
	public static int selectedCustomerIndex;
	public float newPromotionUnit;
	public boolean promotionPriceChangeFlag=false;
	
	Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost:3306/mydb";
    String user = "root";
    String password = "qweasdzxc";
	
	
	PromotionTableInterface cti;
	private JTextField promotionTextField;
	public PromotionAddition(final PromotionTableInterface cti) {
		
		super("Promosyon Ekleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		JLabel lblMteri = new JLabel("Müşteri");
		lblMteri.setBounds(12, 12, 70, 15);
		getContentPane().add(lblMteri);
		
		JComboBox customerComboBox = new JComboBox();
		customerComboBox.setBounds(84, 12, 170, 24);
		getContentPane().add(customerComboBox);
		
		JLabel lblrn = new JLabel("Ürün");
		lblrn.setBounds(298, 12, 70, 15);
		getContentPane().add(lblrn);
		
		
		JComboBox productComboBox = new JComboBox();
		productComboBox.setBounds(357, 12, 170, 24);
		getContentPane().add(productComboBox);
		
		promotionTextField = new JTextField();
		promotionTextField.setBounds(164, 59, 138, 24);
		getContentPane().add(promotionTextField);
		promotionTextField.setColumns(10);
		
		JButton addButton = new JButton("Ekle");
		addButton.setBounds(322, 59, 100, 25);
		getContentPane().add(addButton);
		
		addButton.addMouseListener(new MouseListener() {
			
			
			@Override
			public void mouseClicked(MouseEvent e) {
				
					try{
				    promotionUnit=Integer.parseInt(promotionTextField.getText());
					}catch(NullPointerException ex){
						promotionUnit=0;
					}
				

					
					if(customerFlag && productFlag && promotionUnit>0){
			 	
							try {
									con = (Connection) DriverManager.getConnection(url, user, password);
									st = (Statement) con.createStatement();
									rs=st.executeQuery("SELECT * from promotion where promotion_customer_id='"+customers[selectedCustomerIndex-1].getCustomerId()+"'" +
											"AND promotion_product_id='"+products[selectedProductIndex-1].getProductId()+"' ");
									int i=0,counter=0;
									while(rs.next())
										++counter;
									
									if(counter<1){
										System.out.println("First Time Promotion addition for these components");
										
										st.executeUpdate("INSERT INTO promotion (promotion_customer_id,promotion_product_id,promotion_unit) " +
												"VALUES('"+customers[selectedCustomerIndex-1].getCustomerId()+"','"+products[selectedProductIndex-1].getProductId()+"'," +
														"'"+promotionUnit+"')");
										
										int messageType = JOptionPane.PLAIN_MESSAGE;
							            JOptionPane.showMessageDialog(null, "Kayıt Alınmıştır", "Uyarı!!", messageType);
										cti.addNewItem();
										setVisible(false);
										dispose();
									}
									else{
										int messageType = JOptionPane.PLAIN_MESSAGE;
							            JOptionPane.showMessageDialog(null, "Promosyon Bilgisi Sistemde Kayıtlı", "Hata!!", messageType);
									}
		            
									
									con.close();
							} catch (SQLException ex) {
								Logger lgr = Logger.getLogger(main.class.getName());
								lgr.log(Level.SEVERE, ex.getMessage(), ex);

							} finally {
								try {
									if (rs != null) {
										rs.close();
									}
									if (st != null) {
										st.close();
										}
									if (con != null) {
										con.close();
									}

								} catch (SQLException ex) {
									Logger lgr = Logger.getLogger(main.class.getName());
									lgr.log(Level.WARNING, ex.getMessage(), ex);
								}
							}
				
				
				
							
			        
				}
				
				
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
	 	
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);
            st = (Statement) con.createStatement();
            rs=st.executeQuery("SELECT * from customer WHERE activity=1 order by customer_name");
            int i=0,counter=0;
            while(rs.next())
            	++counter;
            
            customerComboBox.addItem("Müşteri Adı");
            if(counter>0){
            rs.first();
            customers=new Customer[counter];
            customers[i]=new Customer();
            customers[i].setCustomerName(rs.getString("customer_name"));
        	customers[i].setCustomerId(rs.getInt("customer_id"));
            i++;
            while(rs.next())
            {
            	customers[i]=new Customer();
            	customers[i].setCustomerName(rs.getString("customer_name"));
            	customers[i].setCustomerId(rs.getInt("customer_id"));
            	++i;
            }
            
            }
            
            for(int m=0;m<customers.length;m++){
            	customerComboBox.addItem(customers[m].getCustomerName());
            }
            
            
            con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
        
        
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);
            st = (Statement) con.createStatement();
            // TG 03-12-2012 urun listesi yerine musteri listesinin sirali olarak getirilmesi.
            //rs=st.executeQuery("SELECT * from product WHERE activity=1 order by product_name");
            rs=st.executeQuery("SELECT * from product WHERE activity=1");
            int i=0,counter=0;
            while(rs.next())
            	++counter;
            rs.first();
            productComboBox.addItem("Ürün Adı");
            if(counter>0){
            products=new Product[counter];
            products[i]=new Product();
            products[i].setProductName(rs.getString("product_name"));
            products[i].setProductId(rs.getInt("product_id"));
            i++;
            while(rs.next())
            {
            	products[i]=new Product();
            	products[i].setProductName(rs.getString("product_name"));
                products[i].setProductId(rs.getInt("product_id"));
            		++i;
        
            }
            
            }
            
            for(int m=0;m<products.length;m++){
            	productComboBox.addItem(products[m].getProductName());
            }
            con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }        
		setVisible(true);  
		
		customerComboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				
				
                JComboBox comboBox = (JComboBox) event.getSource();
       	     
                //
                // Print the selected items and the action command.
                //
                Object selected = comboBox.getSelectedItem();
                selectedCustomerIndex=comboBox.getSelectedIndex();
                System.out.println("Selected Customer  = " + customers[selectedCustomerIndex-1].getCustomerName());
                String command = event.getActionCommand();
                System.out.println("Action Command = " + command);
                
                if(selected.toString().equals("Müşteri Adı")){
                	customerFlag=false;
                }
                else{
                	customerFlag=true;
                }
                
                
				
				
				
				
				
				
				
			}
		});
		
		
		productComboBox.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				
				
                JComboBox comboBox = (JComboBox) event.getSource();
       	     
                //
                // Print the selected items and the action command.
                //
                Object selected = comboBox.getSelectedItem();
                selectedProductIndex=comboBox.getSelectedIndex();
                System.out.println("Selected Product  = " + products[selectedProductIndex-1].getProductName());
                String command = event.getActionCommand();
                System.out.println("Action Command = " + command);
                
                if(selected.toString().equals("Ürün Adı")){
                	productFlag=false;
                }
                else{
                	productFlag=true;
                }
                
                
                
                
			}
		});

	
		
	}
	
	
	
	
	
}
